package com.wgts.wgts.mvp.view.activity.goodsinfo;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wgts.wgts.R;
import com.wgts.wgts.base.LazyBaseFragment;
import com.wgts.wgts.control.RoundBackgroundColorSpan;
import com.wgts.wgts.control.layout.SlideDetailsLayout;
import com.wgts.wgts.control.scrollview.GradationScrollView;
import com.wgts.wgts.dagger.ComponentHolder;
import com.wgts.wgts.dagger.component.DaggerJDHeaderFragmentComponent;
import com.wgts.wgts.dagger.module.JDHeaderFragmentMoudle;
import com.wgts.wgts.localbean.LocalProductInfo;
import com.wgts.wgts.localbean.ProductImages;
import com.wgts.wgts.localbean.ProductInfoAttribute;
import com.wgts.wgts.localbean.ProductSpecifications;
import com.wgts.wgts.mvp.presenter.IJDHeaderFragmentPersenter;
import com.wgts.wgts.mvp.view.IJDHeaderFragmentView;
import com.wgts.wgts.mvp.view.activity.login.LoginActivity;
import com.wgts.wgts.netmodle.resp.ProductEvaluateEntity;
import com.wgts.wgts.netmodle.resp.ProductInfoEntity;
import com.wgts.wgts.tools.AppInfor;
import com.wgts.wgts.tools.MoHuGlide;
import com.wgts.wgts.tools.Tools;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import java.util.ArrayList;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;

public class JDHeaderFragment extends LazyBaseFragment implements IJDHeaderFragmentView {


    @BindView(R.id.img_product)
    MZBannerView imgProduct;
    @BindView(R.id.tv_banner)
    TextView tvBanner;
    @BindView(R.id.relative_banner)
    RelativeLayout relativeBanner;
    @BindView(R.id.tv_util)
    TextView tvUtil;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.product_sale)
    TextView productSale;
    @BindView(R.id.tv_old_price)
    TextView tvOldPrice;
    @BindView(R.id.linear_old_price)
    LinearLayout linearOldPrice;
    @BindView(R.id.relative_product_price)
    RelativeLayout relativeProductPrice;
    @BindView(R.id.tv_product_name)
    TextView tvProductName;
    @BindView(R.id.linear_share)
    LinearLayout linearShare;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.img_right)
    ImageView imgRight;
    @BindView(R.id.tv_product_attribute)
    TextView tvProductAttribute;
    @BindView(R.id.releative_select)
    RelativeLayout releativeSelect;
    @BindView(R.id.tv_trans)
    TextView tvTrans;
    @BindView(R.id.tv_product_trans)
    TextView tvProductTrans;
    @BindView(R.id.view_bg)
    View viewBg;
    @BindView(R.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R.id.save_view)
    LinearLayout saveView;
    @BindView(R.id.gsv)
    GradationScrollView gsv;

    @BindView(R.id.sdl)
    SlideDetailsLayout sdl;
    private int mHeight;

    Unbinder unbinder;

    private LinearLayoutManager linearLayoutManager;

    private static final String BANNER = "banner";

    private static final String BIGIMG = "bigImg";

    private static final String INFO = "info";

    private static final String ATTRIBUTE = "attribute";

    private static final String SPECIFICATIONS = "specifications";


    public static final String JOIN_TYPE = "JOIN_TYPE";


    //普通商品
    public static final String NOMAL = "NOMAL";

    //限时抢购
    public static final String TIME_ACTION = "TIME_ACTION";

    public static final String VIP_GOOD = "VIP_GOOD";

    private int updownState;

    private FragmentToActivity fragmentToActivity;


    @Inject
    public IJDHeaderFragmentPersenter persenter;


    private ArrayList<ProductImages> banner;
    private ArrayList<ProductImages> detailImages;
    private LocalProductInfo productInfo;
    private ArrayList<ProductInfoAttribute> attribute;
    private ArrayList<ProductSpecifications> specifications;

    private ShareDialogFragment shareDialogFragment;


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        fragmentToActivity = (FragmentToActivity) context;
    }


    @Override
    protected void loadData() {

    }

    @Override
    public void init() {

        DaggerJDHeaderFragmentComponent
                .builder()
                .appComponent(ComponentHolder.getInstance().getAppComponent())
                .jDHeaderFragmentMoudle(new JDHeaderFragmentMoudle(this))
                .build()
                .inject(this);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.jd_fragment, container, false);

        unbinder = ButterKnife.bind(this, view);
        initBundle();
        initView();
        return view;
    }


    private void initBundle() {
        Bundle bundle = getArguments();
        banner = bundle.getParcelableArrayList(BANNER);
        detailImages = bundle.getParcelableArrayList(BIGIMG);
        productInfo = bundle.getParcelable(INFO);
        attribute = bundle.getParcelableArrayList(ATTRIBUTE);
        specifications = bundle.getParcelableArrayList(SPECIFICATIONS);

        shareDialogFragment = ShareDialogFragment.getInstance(productInfo, AppInfor.getInstance().getInviteCode());
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        persenter.removeTimeCount();
    }


    public static JDHeaderFragment getInstance(ArrayList<ProductImages> banner, ArrayList<ProductImages> detailImages
            , LocalProductInfo productInfo, ArrayList<ProductInfoAttribute> attribute, ArrayList<ProductSpecifications> specifications, String Type) {
        JDHeaderFragment fragment = new JDHeaderFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList(BANNER, banner);
        bundle.putParcelableArrayList(BIGIMG, detailImages);
        bundle.putParcelable(INFO, productInfo);
        bundle.putParcelableArrayList(ATTRIBUTE, attribute);
        bundle.putParcelableArrayList(SPECIFICATIONS, specifications);
        bundle.putString(JOIN_TYPE, Type);
        fragment.setArguments(bundle);
        return fragment;
    }


    @OnClick(R.id.releative_select)
    public void onViewClicked() {
        ((JDGoodinfoActivity) getActivity()).showDialog();
    }





    /*----------------------------------------------限时抢购&普通商品---------------------------------------------------*/

    @Override
    public void upDownProductResult(int state) {

    }


    public void updateAttribute(String attribute) {
        tvProductAttribute.setText(attribute);
    }

    /**
     * 限时抢购
     */
    private void initTimeAction() {
//        relativeAction.setVisibility(View.GONE);
//        persenter.startTimeCount(productInfo.restTime);
//        linearLottery.setVisibility(View.GONE);
//        relativeAction.setVisibility(View.VISIBLE);
//        linearJoinFriend.setVisibility(View.GONE);
//        linearGuess.setVisibility(View.GONE);
//        releativeSelect.setClickable(true);


    }

    public void actionProduct(ProductInfoEntity productInfo) {
        if (productInfo.status != null) {
            switch (productInfo.status) {
//                case "ACTIVE":
//                    tvRelativeActionTitle.setText("距离活动结束");
//                    break;
//                case "PENDING":
//                    tvRelativeActionTitle.setText("距离活动开始");
//                    break;
//                case "DELETED":
//                    relativeAction.setVisibility(View.INVISIBLE);
//                    break;
            }
        }

//        if (productInfo.restTime > 0) {
//            relativeAction.setVisibility(View.VISIBLE);
//            persenter.startTimeCount(productInfo.restTime);
//        } else {
//            relativeAction.setVisibility(View.INVISIBLE);
//        }
    }

    /**
     * 普通界面
     */
    private void initNomalView() {
        releativeSelect.setClickable(true);
//        linearLottery.setVisibility(View.GONE);
//        relativeAction.setVisibility(View.VISIBLE);
//        linearJoinFriend.setVisibility(View.GONE);
//        linearGuess.setVisibility(View.GONE);
    }

    private void initVipGood() {
        releativeSelect.setClickable(true);
//        linearLottery.setVisibility(View.GONE);
//        relativeAction.setVisibility(View.GONE);
//        linearJoinFriend.setVisibility(View.GONE);
//        linearGuess.setVisibility(View.GONE);
        tvOldPrice.setVisibility(View.INVISIBLE);
    }

    /*----------------------------------------------限时抢购&普通商品---------------------------------------------------*/

    /*---------------------------------------------共通模块---------------------------------------------------------*/
    private void initView() {


        initBanner();


        persenter.productEvaluate(String.valueOf(productInfo.productId), 1, 3);

        initProductInfo();


        initRecycleView();

        initModel();
    }


    @Override
    public void evaluateResult(ProductEvaluateEntity evaluateEntity) {

//        if (evaluateEntity.list.size() == 0) {
//            linearAllEvaluate.setVisibility(View.GONE);
//            viewBg.setVisibility(View.GONE);
//        } else {
//            linearAllEvaluate.setVisibility(View.VISIBLE);
//            viewBg.setVisibility(View.VISIBLE);
//        }

        for (ProductEvaluateEntity.Evaluate evaluate : evaluateEntity.list) {

//            tvProductEvaluate.setText(evaluateEntity.rate);

            View view = LayoutInflater.from(getContext()).inflate(R.layout.evaluate_view_holder, null);
            CircleImageView circleImageView = view.findViewById(R.id.img_customer_heard);
            TextView customerName = view.findViewById(R.id.tv_customer_name);
            TextView evaluateTime = view.findViewById(R.id.tv_evaluate_date);
            ImageView startOne = view.findViewById(R.id.one_start);
            ImageView starttwo = view.findViewById(R.id.two_start);
            ImageView startthree = view.findViewById(R.id.thre_start);
            ImageView startfour = view.findViewById(R.id.four_start);
            ImageView startfive = view.findViewById(R.id.five_start);
            TextView tvEvaluate = view.findViewById(R.id.tv_evaluate);
            TextView tvSpecifications = view.findViewById(R.id.tv_specifications);

            tvEvaluate.setText(evaluate.evaluateContent);
            MoHuGlide.getInstance().glideImg(getContext(), evaluate.userImage, circleImageView);
            customerName.setText(evaluate.userNickname);
            evaluateTime.setText(evaluate.evaluateTime);
            tvSpecifications.setText(evaluate.productStandard);
            switch (evaluate.evaluateScore1) {
                case "0":
                    startOne.setVisibility(View.INVISIBLE);
                    starttwo.setVisibility(View.INVISIBLE);
                    startthree.setVisibility(View.INVISIBLE);
                    startfour.setVisibility(View.INVISIBLE);
                    startfive.setVisibility(View.INVISIBLE);
                    break;
                case "1":
                    startOne.setVisibility(View.VISIBLE);
                    starttwo.setVisibility(View.INVISIBLE);
                    startthree.setVisibility(View.INVISIBLE);
                    startfour.setVisibility(View.INVISIBLE);
                    startfive.setVisibility(View.INVISIBLE);
                    break;
                case "2":
                    startOne.setVisibility(View.VISIBLE);
                    starttwo.setVisibility(View.VISIBLE);
                    startthree.setVisibility(View.INVISIBLE);
                    startfour.setVisibility(View.INVISIBLE);
                    startfive.setVisibility(View.INVISIBLE);
                    break;
                case "3":
                    startOne.setVisibility(View.VISIBLE);
                    starttwo.setVisibility(View.VISIBLE);
                    startthree.setVisibility(View.VISIBLE);
                    startfour.setVisibility(View.INVISIBLE);
                    startfive.setVisibility(View.INVISIBLE);
                    break;
                case "4":
                    startOne.setVisibility(View.VISIBLE);
                    starttwo.setVisibility(View.VISIBLE);
                    startthree.setVisibility(View.VISIBLE);
                    startfour.setVisibility(View.VISIBLE);
                    startfive.setVisibility(View.INVISIBLE);
                    break;
                case "5":
                    startOne.setVisibility(View.VISIBLE);
                    starttwo.setVisibility(View.VISIBLE);
                    startthree.setVisibility(View.VISIBLE);
                    startfour.setVisibility(View.VISIBLE);
                    startfive.setVisibility(View.VISIBLE);
                    break;
            }


//            lineaEvaluate.addView(view);
//            View line = LayoutInflater.from(getContext()).inflate(R.layout.linea_linear, null);
//            lineaEvaluate.addView(line);
        }

    }


    private void initBanner() {
        DisplayMetrics outMetrics = Tools.metrics(getActivity());
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(outMetrics.widthPixels, outMetrics.widthPixels);
        relativeBanner.setLayoutParams(layoutParams);
        tvBanner.setText(1 + "/" + banner.size());
        imgProduct.setIndicatorVisible(false);
        imgProduct.start();
        imgProduct.setPages(banner, new MZHolderCreator() {
            @Override
            public MZViewHolder createViewHolder() {
                return new ProductBanner();
            }
        });

        imgProduct.addPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                if (banner != null && tvBanner != null) {
                    tvBanner.setText(i + 1 + "/" + banner.size());
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }


    private void initProductInfo() {
        if (AppInfor.getInstance().getUserState() > 1) {
//            linearGetPrice.setVisibility(View.VISIBLE);
            linearOldPrice.setVisibility(View.GONE);
        } else {
//            linearGetPrice.setVisibility(View.GONE);
            linearOldPrice.setVisibility(View.VISIBLE);
        }


        tvPrice.setText(productInfo.retailPrice);
        tvOldPrice.setText("￥" + productInfo.marketPrice);
        tvOldPrice.setPaintFlags(tvOldPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
//        tvGetPrice.setText("可赚:" + productInfo.marketPrice);
        productSale.setText("已售" + productInfo.sellCount);


        String str1 = "微广自营";

        SpannableString spannableString = new SpannableString("微广自营" + productInfo.productName);
        int bgColor = Color.parseColor("#ff8041");
        int textColor = Color.parseColor("#ff8041");
        RoundBackgroundColorSpan span = new RoundBackgroundColorSpan(bgColor, textColor, 5);
        spannableString.setSpan(span, 0, str1.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);


        tvProductName.setText(spannableString);
    }


    private void initRecycleView() {
        linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(linearLayoutManager);
        recycleView.setAdapter(new GoodInfoPictureAdapter(getContext(), detailImages, productInfo.productSubtitle));
    }


    private void initModel() {
        switch (getArguments().getString(JOIN_TYPE)) {
            case NOMAL:
                initNomalView();
                break;
            case TIME_ACTION:
                initTimeAction();
                break;
            case VIP_GOOD:
                initVipGood();
                break;
        }

//        if (productInfo.restTime > 0) {
//            relativeAction.setVisibility(View.VISIBLE);
//        } else {
//            relativeAction.setVisibility(View.INVISIBLE);
//        }
    }

    @Override
    public void timeAction(final String time) {
        if (getActivity() == null)
            return;
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {

//                String[] times = time.split(":");
//                if (tvHours != null) {
//                    tvHours.setText(times[0]);
//                }
//                if (tvMinute != null) {
//                    tvMinute.setText(times[1]);
//                }
//                if (tvMillons != null) {
//                    tvMillons.setText(times[2]);
//                }
            }
        });
    }

    @Override
    public void timeOverRefresh() {
//        ((JDGoodinfoActivity) getActivity()).refreshActionGood();
    }

    public interface FragmentToActivity {
        void goToEventment();
    }


    /*---------------------------------------------共通模块---------------------------------------------------------*/
}
